from django.shortcuts import render, HttpResponse, redirect
import random
from utils.tencent.sms_code import send_sms_single
from django.conf import settings
from .forms import UserInfoForms
from django.views import View
from django_redis import get_redis_connection


def send_sms(request):
    """ 注册发送短信"""
    # phone = request.POST.get('phone')
    # tpl = request.GET.get('tpl')
    # template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    #
    # if not template_id:
    #     return HttpResponse('模板不存在')
    #
    # code = random.randrange(1000, 9999)
    # # 注册
    # res = send_sms_single(phone, template_id, [code, 10])
    # conn = get_redis_connection('default')
    # conn.set(phone, code)
    # if res['result'] == 0:
    #     return HttpResponse('成功')
    # else:
    #     return HttpResponse(res['errmsg'])
    return HttpResponse('成功')


def log_in(request):
    return render(request, 'login.html')


class Register(View):
    def get(self, request):
        form_obj = UserInfoForms()
        return render(request, 'register.html', {'form_obj': form_obj})

    def post(self, request):
        form_obj = UserInfoForms(data=request.POST)
        if form_obj.is_valid():
            form_obj.save()
            return redirect('index')

        return render(request, 'register.html', {'form_obj': form_obj})


def index(request):
    return render(request, 'index.html')
